import os
import shutil
from AppManager.Mysql import MysqlPool
from HostManager import DownloadSftp


hostdict = {}
CronDict = {"Op主机": {}}


# 获取OP所在本机的定时调度
def getSelfCronDict():
    global CronDict
    cronpath = '/var/spool/cron'
    cronfiles = os.listdir(cronpath)
    i = 0
    for file in cronfiles:
        CronDict["Op主机"][file] = {"data": []}
        if not i:
            CronDict["Op主机"][file]["active"] = " active"
            CronDict["Op主机"][file]["show"] = " show active"
            i = 1
        f = open(cronpath + "/" + file)
        crons = f.readlines()
        for cron in crons:
            CronDict["Op主机"][file]["data"].append(cron)
    return CronDict


# 获取已有资产的定时调度
def getAllCronDict():
    global CronDict
    shutil.rmtree('/tmp/remotecron')
    for hostname, hostdata in hostdict.items():
        CronDict[hostname] = {}
        RemoteHost = {
            "host": hostdata["ip"],
            "port": hostdata["port"],
            "username": hostdata["user"],
            "password": hostdata["password"]
        }
        localpath = "/tmp/remotecron/" + hostname
        remotepath = "/var/spool/cron"
        DownloadSftp.DownloadSftp(RemoteHost, localpath, remotepath)
        for path, dirlist, filelist in os.walk(localpath):
            i = 0
            for file in filelist:
                CronDict[hostname][file] = {"data": []}
                if not i:
                    CronDict[hostname][file]["active"] = " active"
                    CronDict[hostname][file]["show"] = " show active"
                    i = 1
                filename = os.path.join(path, file)
                with open(filename, "r", encoding="utf-8") as f:
                    crons = f.readlines()
                    for cron in crons:
                        CronDict[hostname][file]["data"].append(cron)


def newCronDict():
    gethostlist()
    getSelfCronDict()
    getAllCronDict()


def gethostlist():
    global hostdict
    sql = "SELECT * FROM `host`"
    hsotres = MysqlPool(sql, 99)
    sql = "SELECT * FROM `host_dev`"
    hsotdevres = MysqlPool(sql, 99)
    i = 0
    for host in hsotres:
        hostdict[host["hostname"]] = {
            "ip": host["ip"],
            "port": host["ssh_port"],
            "user": hsotdevres[i]["Suser"],
            "password": hsotdevres[i]["Spasswd"]
        }
    return hostdict


newCronDict()
